#coding:utf-8

import os.path

import urllib2,httplib

class UrlRedirectHandler(urllib2.HTTPRedirectHandler):
	def http_error_301(self,req,fp,code,msg,headers):
		result = urllib2.HTTPRedirectHandler.http_error_301(
			self,req,fp,code,msg,headers)
		result.status = code
		return result

	def http_error_302(self,req,fp,code,msg,headers):
		result = urllib2.HTTPRedirectHandler.http_error_302(
			self,req,fp,code,msg,headers)
		result.status = code
		return result

def _redirect_uri(uri):
	request = urllib2.Request(uri)
	opener = urllib2.build_opener(UrlRedirectHandler)
	f = opener.open(request)
	return f.url

def redirect_uri(uri,redirect=False):
	if redirect:
		return _redirect_uri(uri)
	if uri.startswith("http://go.rss.sina.com.cn/redirect.php?url="):
		return uri[len('http://go.rss.sina.com.cn/redirect.php?url='):]
	return uri


def initUri(filename):
	U = set()
	with open(filename,mode='r') as f:
		for line in f:
			u = line.strip().decode('utf-8')
			U.add(u)
	return U

def saveUri(U,filename):
	with open(filename,mode='w') as f:
		for u in U:
			line = u.encode('utf-8')+'\n'
			f.write(line)

class RssUri(object):

	def __init__(self, location):
		self.location = location
		if os.path.exists(location):
			self.U = initUri(location)
		else:
			self.U = set()

	def size(self):
		return len(self.U)

	def is_in(self,uri):
		if uri in self.U:
			return True
		else:
			return False

	def insert(self,us):
		with open(self.location,mode='a') as f:
			for u in us:
				if u not in self.U:
					line = u.encode('utf-8')+'\n'
					f.write(line)
					self.U.add(u)

		#for u in us:
		#	self.U.add(us)

	def save(self, location=None):
		if location == None:
			saveUri(self.U, self.location)
		else:
			saveUri(self.U, location)

